import { fetchInventory, addInventoryItem, fetchResourceOptions } from '@/api/inventory';

const state = {
  inventory: [],
  resourceOptions: [],
  warningThreshold: 5
};

const mutations = {
  SET_INVENTORY(state, inventory) {
    state.inventory = inventory;
  },
  ADD_INVENTORY_ITEM(state, newItem) {
    const existingItemIndex = state.inventory.findIndex(item => item.materialId === newItem.materialId);
    if (existingItemIndex !== -1) {
      state.inventory[existingItemIndex].quantity += newItem.quantity;
    } else {
      state.inventory.push(newItem);
    }
  },
  SET_RESOURCE_OPTIONS(state, options) {
    state.resourceOptions = options;
  }
};

const actions = {
  async fetchInventory({ commit }) {
    try {
      const response = await fetchInventory();
      commit('SET_INVENTORY', response.data); // 确保API返回的数据格式正确
    } catch (error) {
      console.error('Failed to fetch inventory:', error.message);
    }
  },
  async addInventoryItem({ commit }, newItem) {
    try {
      await addInventoryItem(newItem);
      commit('ADD_INVENTORY_ITEM', newItem);
      return true;
    } catch (error) {
      console.error('Failed to add inventory item:', error.message);
      return false;
    }
  },
  async fetchResourceOptions({ commit }) {
    try {
      const response = await fetchResourceOptions();
      commit('SET_RESOURCE_OPTIONS', response.data);
    } catch (error) {
      console.error('Failed to fetch resource options:', error.message);
    }
  }
};

const getters = {
  getStockMessage: (state) => (quantity) => quantity <= state.warningThreshold ? '库存告急' : '库存充足',
  getStockStatus: (state) => (quantity) => quantity <= state.warningThreshold ? 'warning' : ''
};

export default {
  namespaced: true,
  state,
  mutations,
  actions,
  getters
};